#coding=utf-8
from datetime import datetime
from tokenize import cookie_re

import requests
from docx import Document
from docx.shared import Inches, Cm, Pt, Mm
from docx.oxml import OxmlElement
from io import BytesIO
from docxtpl import DocxTemplate,InlineImage
from datetime import datetime
import jinja2
import uuid

save_path = "./word/" #文件保存路径
template_path = "./templates/Paopai.docx" #模板保存路径

def get_table1(jh: str, cookie: str):
    cookie = {"cookie": cookie}
    response = requests.get(f"http://10.84.4.74/yyqer/jtbb/zjjcsj_json.jsp?jh={jh}", cookies=cookie)
    data1 = response.json()["res"][0]
    data2 = response.json()["res2"][0]
    data3 = response.json()["res2"][1]
    return {
        "d1": data1[1],
        "d2": data1[2],
        "d3": data1[24],
        "d4": data1[3],
        "d5": data1[4],
        "d6": data1[5],
        "d7": data1[6],
        "d8": data1[7],
        "d9": data1[8],
        "d10": data1[9],
        "d11": data1[10],
        "d12": data1[23],
        "d13": data2[6],
        "d14": data2[7],
        "d15": data2[8],
        "d16": data3[6],
        "d17": data3[7],
        "d18": data3[8],
        "d19": data2[4],
        "d20": data2[5],
        "d21": data2[2],
        "d22": data2[3],
        "d23": data3[4],
        "d24": data3[5],
        "d25": data3[2],
        "d26": data3[3],
        "d27": data1[11],
        "d28": data1[19],
        "d29": data1[20],
        "d30": data1[21],
        "d31": data1[13],
        "d32": data1[16],
        "d33": data1[12],
        "d34": data1[14],
        "d35": data1[25],
        "d36": data1[25],
        "d37": data1[22],
        "d38": data1[18],
        "d39": data1[17],
        "d40": data1[27],
        "d41": data1[26],
    }

def get_images(doc: DocxTemplate, jh: str, cookie: str):
    cookie = {"cookie": cookie}
    response = requests.get("http://10.84.4.74/yyqer/txgl/readmap.jsp?TXBH=12026", cookies=cookie)
    data = response.content
    image_stream = BytesIO(data)
    image1 = InlineImage(doc, image_stream, width=Cm(16.00),height=Cm(8.56))
    image2 = InlineImage(doc, image_stream, width=Cm(16.00), height=Cm(11.90))
    return {
        "image1": image1,
        "image2": image2,
    }

def get_data1_1(jh: str, cookie: str):
    cookie = {"cookie": cookie}
    response = requests.get(f"http://10.84.4.74/yyqer/idoc/cqgc/data/readjson1.1.1.jsp?jh={jh}",cookies=cookie)
    data = response.json()
    return {
        "d1": data["DLWZ"],
        "d2": data["WZCWMC"],
    }

def get_table2(jh: str, cookie: str):
    cookie = {"cookie": cookie}
    response = requests.get(f"http://10.84.4.74/yyqer/idoc/cqgc/table/tg1.1.6_json.jsp?jh={jh}",cookies=cookie)
    data = response.json()["res"]
    table2 = []
    for i in range(len(data)):
        table2.append({
            "d1": data[i][0],
            "d2": data[i][1],
            "d3": data[i][2],
            "d4": data[i][3],
            "d5": data[i][4],
            "d6": data[i][5],
            "d7": data[i][6],
        })
    return table2

def get_data1_2(jh: str, cookie: str):
    cookie = {"cookie": cookie}
    response = requests.get(f"http://10.84.4.74/yyqer/idoc/cqgc/data/readjson1.2.1.jsp?jh={jh}", cookies=cookie)
    data = response.json()
    return {
        "d1": data["SKRQ4B"],
        "d2": data["ABD1"],
        "d3": data["ABD2"],
        "d4": data["ABD3"],
        "d5": data["ABD4"],
        "d6": data["ABD5"],
        "d7": data["BBD1"],
        "d8": data["BBD2"],
        "d9": data["BBD3"],
        "d10": data["BBD4"],
        "d11": data["BBD5"],
        "d12": data["WZRQ5B"],
        "d13": data["CBD1"],
        "d14": data["CBD2"],
        "d15": data["CBD3"],
        "d16": data["CBD4"],
        "d17": data["CBD5"],
    }

def get_data1_3(jh: str, cookie: str):
    cookie = {"cookie": cookie}
    response = requests.get(f"http://10.84.4.74/yyqer/idoc/cqgc/data/readjson1.3.1.jsp?jh={jh}", cookies=cookie)
    data = response.json()
    return {
        "d1": data["DDB20A"],
        "d2": data["DDB20B"],
        "d3": data["DDB20C"],
        "d4": data["DDB20D"],
        "d5": data["DDB20E"],
        "d6": data["DDB20F"],
        "d7": data["DDB20G"],
        "d8": data["DDB20H"],
    }

def get_data1_4(jh: str, cookie: str):
    cookie = {"cookie": cookie}
    response = requests.get(f"http://10.84.4.74/yyqer/idoc/cqgc/data/readjson1.4.1.jsp?jh={jh}", cookies=cookie)
    data = response.json()
    return {
        "d1": data["YLDS1"],
        "d2": data["SKJD_MIN"],
        "d3": data["SKJD_MAX"],
        "d4": data["YLRQ1"],
        "d5": data["YLZSL2"],
        "d6": data["YLDS1B"],
        "d7": data["YLZSL1"],
        "d8": data["YLZSL2"],
        "d9": data["YLZSL3"],
    }

def get_data1_5(jh: str, cookie: str):
    cookie = {"cookie": cookie}
    response = requests.get(f"http://10.84.4.74/yyqer/idoc/cqgc/data/readjson1.5.1.jsp?jh={jh}", cookies=cookie)
    data = response.json()
    return {
        "d1": data["DDB2XA"],
        "d2": data["DDB2XC"],
        "d3": data["DDB2XD"],
        "d4": data["DDB2XE"],
    }

def get_table3(jh: str, cookie: str):
    cookie = {"cookie": cookie}
    response = requests.get(f"http://10.84.4.74/yyqer/idoc/cqgc/table/qc1.5.3_json.jsp?jh={jh}",cookies=cookie)
    data = response.json()["res"]
    table3 = []
    for i in range(len(data)):
        table3.append({
            "d1": data[i][0],
            "d2": data[i][1],
            "d3": data[i][2],
            "d4": data[i][3],
        })
    return table3

def get_data1_6(jh: str, cookie: str):
    cookie = {"cookie": cookie}
    response = requests.get(f"http://10.84.4.74/yyqer/idoc/cqgc/data/readjson1.6.1.jsp?jh={jh}", cookies=cookie)
    data = response.json()
    return {
        "d1": data["TCRQ1"],
        "d2": data["JKYL1"],
        "d3": data["CQL1"],
        "d4": data["CSL1"],
        "d5": data["TCRQ2"],
        "d6": data["JKYL2"],
        "d7": data["CQL2"],
        "d8": data["CSL2"],
        "d9": data["LJCQ3"],
        "d10": data["LJCS3"],
        "d11": data["QJFPL"],
    }

def get_table4(jh: str, cookie: str):
    cookie = {"cookie": cookie}
    response = requests.get(f"http://10.84.4.74/yyqer/idoc/cqgc/table/qfx2.4.3_json.jsp?jh={jh}",cookies=cookie)
    data = response.json()["res"][0]
    table4 = []
    table4.append({
        "d1": data[0],
        "d2": data[1],
        "d3": data[2],
        "d4": data[3],
        "d5": data[4],
        "d6": data[5],
        "d7": data[6],
        "d8": data[7],
        "d9": data[8],
        "d10": data[9],
        "d11": data[10],
        "d12": data[11],
        "d13": data[12],
    })
    return table4

def get_table6(jh: str, cookie: str):
    cookie = {"cookie": cookie}
    response = requests.get(f"http://10.84.4.74/yyqer/idoc/cqgc/table/jxyg_json.jsp?jh={jh}",cookies=cookie)
    data = response.json()["rs5"]
    table6 = []
    for i in range(len(data)):
        table6.append({
            "d1": data[i][0],
            "d2": data[i][1],
            "d3": data[i][2],
            "d4": data[i][3],
            "d5": data[i][4],
            "d6": data[i][5],
            "d7": data[i][6],
            "d8": data[i][7],
            "d9": data[i][8],
            "d10": data[i][9],
            "d11": data[i][10],
            "d12": data[i][11],
        })
    return table6

def get_table7(jh: str, cookie: str):
    cookie = {"cookie": cookie}
    response = requests.get(f"http://10.84.4.74/yyqer/idoc/cqgc/table/jx9.2_json.jsp?jh={jh}",cookies=cookie)
    data = response.json()["res"]
    table7 = []
    for i in range(len(data)):
        table7.append({
            "d1": data[i][0],
            "d2": data[i][1],
            "d3": data[i][2],
            "d4": data[i][3],
            "d5": data[i][4],
            "d6": data[i][5],
            "d7": data[i][6],
            "d8": data[i][7],
            "d9": data[i][8]
        })
    return table7
"""
传入参数，返回文件名
"""
def create_JianGuan_word(jh: str, cookie: str
                         ,data1_7: str,data1_8: str
                         ,data1_9: str,data2_2_1: str,data2_2_2: str
                         ,data2_3_1: str,data2_3_2: str
                         ,data2_4: str,data2_5: str
                         ,data2_6_1: str,data2_6_2: str):

    doc = DocxTemplate(template_path)

    table1 = get_table1(jh, cookie)
    table2 = get_table2(jh, cookie)
    table3 = get_table3(jh, cookie)
    table4 = get_table4(jh, cookie)
    table6 = get_table6(jh, cookie)
    table7 = get_table7(jh, cookie)
    images = get_images(doc,jh, cookie)
    data1_1 = get_data1_1(jh,cookie)
    data1_2 = get_data1_2(jh,cookie)
    data1_3 = get_data1_3(jh,cookie)
    data1_4 = get_data1_4(jh,cookie)
    data1_5 = get_data1_5(jh,cookie)
    data1_6 = get_data1_6(jh,cookie)

    context = {
        "jh": jh,
        "images": images,
        "table1": table1,
        "table2": table2,
        "table3": table3,
        "table4": table4,
        "table6": table6,
        "table7": table7,
        "data1_1": data1_1,
        "data1_2": data1_2,
        "data1_3": data1_3,
        "data1_4": data1_4,
        "data1_5": data1_5,
        "data1_6": data1_6,
        "data1_7": data1_7,
        "data1_8": data1_8,
        "data1_9": data1_9,
        "data2_2_1": data2_2_1,
        "data2_2_2": data2_2_2,
        "data2_3_1": data2_3_1,
        "data2_3_2": data2_3_2,
        "data2_4": data2_4,
        "data2_5": data2_5,
        "data2_6_1": data2_6_1,
        "data2_6_2": data2_6_2,
    }

    doc.render(context)

    clear_blank_line_table = [1,2,3,5,6]
    for i in clear_blank_line_table:
        for row in doc.tables[i].rows:
            if not row.cells[0].text.strip():
                row._element.getparent().remove(row._element)

    file_name = str(datetime.now().timestamp()) + str(uuid.uuid4()) + ".docx"
    path = save_path + file_name
    doc.save(path)
    return file_name

if __name__ == "__main__":
    para = {
        "data1_7" : "焦页1-3HF井于2023年03月21日下入N80油管，管柱底深2646.04m，完井管柱结构从下到上依次为：十字叉+筛管+倒角油管+新内涂层倒角油管+管挂变扣+油管挂",
        "data1_8" : "焦页1-3HF井目前生产情况稳定，未发现明显生产异常。近期生产数据显示套压、油压及产气量保持平稳，日产水量在正常范围内波动，增压开采模式下运行正常。2025年6月19日单井水量核实后略有上升（0.646m³），但仍在可控范围内，暂未采取治理措施。管柱异常记录显示2023年3月下入油管后存在疑似异常但未确诊，当前生产参数未见异常表征。",
        "data1_9" : "焦页1-3HF井目前处于增压开采阶段，日产气量约8500-8900m³，油压维持在1.33-1.37MPa，套压2.0-2.1MPa，水气比0.49-0.64m³/10⁴m³。该井剩余技术可采储量为-0.30×10⁸m³，技术可采储量采出程度已达120.04%，表明已进入开发后期。通过压裂改造历史数据分析，该井水平段长1001m，Ⅱ类气层占比49.05%，具备一定剩余气潜力。建议通过重复压裂或暂堵转向技术改造低效段，优化生产制度控制水气比上升，并加强井筒积液监测与排水措施，以挖掘剩余产能。",
        "data2_2_1" : "利用测试求产数据，建立IPR曲线，并根据2025年5月20日稳定生产数据，油压1.37MPa，日产气量0.8905万方，日产水量0.51方的生产工况下，通过Pipesim软件分析：确定穿孔前储层压力10.51MPa和井底流压8.88MPa，见图2-1。",
        "data2_2_2" : "经2023年3月至2025年5月油管穿孔期间累计产气量12784.998万方，查询单位压降产量663.40万方/MPa，穿孔期间储层压力下降19.27MPa。\n由此，可以得出当前储层压力8.33MPa。",
        "data2_3_1" : "通过计算当前储层压力8.33MPa，储层压力相对较低。",
        "data2_3_2" : "在图2-4中表示，采用内径40.9mm油管生产，产气量1万方/天，对应的井底流压为1.34MPa；而采用50.66mm油管生产，产气量1万方/天，对应的井底流压为1.35MPa，采用60mm油管生产，产气量1万方/天，对应的井底流压为1.36MPa。\n    在图2-5及2-6中可以看出，只有当采用40.9mm油管生产时，全井筒积液速率比小于1，因此采用40.9mm油管生产时井筒不会积液。同时通过设置协调点工作范围，可知采用40.9mm油管生产时，工作点位于设置的协调点工作范围内，说明采用40.9mm油管生产能够达到合理的配产，稳定生产状态。\n    通过综合对比分析，建议优选40.9mm油管生产。",
        "data2_4" : "参考焦页1-3HF井在2019-09-06天然气组分化验分析结果，该井天然气不含H2S，低含CO2，根据Q/SH 0015—2010含硫化氢含二氧化碳气井油套管选用推荐作法，N80EUE扣油管可满足涪陵龙马溪组页岩气井生产需要。同时，为了减缓油管穿孔下入内涂层油管深度依据起出旧油管穿孔点最大深度定，若穿孔点最大深度小于1500m，则下内涂层油管至1500m；若穿孔点最大深度大于1500m，则下内涂层油管至穿孔点最大深度加30m。",
        "data2_5" : "为便于排出井筒积液，油管底部带喇叭口和筛管，下至斜深2646.04m，垂深2435.88m，井斜角70.8°。距离A靶点斜深2769.00m，垂深2435.88m；距离射孔顶界斜深3765m，垂深2435.88m。\n    完井管柱结构为：十字叉+筛管+倒角油管+新内涂层倒角油管+管挂变扣+油管挂（见图2-8）。",
        "data2_6_1" : "本井选用的N80 EUE油管抗内外压屈服强度均大于55MPa，以安全系数1.25计算，地层压力应小于44MPa，而涪陵龙马溪页岩气储层地层压力小于30MPa，故不计算油管抗压和抗挤强度，只计算抗拉强度。抗拉强度计算表见表2-2。",
        "data2_6_2" : "计算公式为：安全系数=抗拉屈服强度/井口处油管拉力\n油管下至井深2646.04m，考虑到井斜因素，油管重量被井眼轨迹分解，作用到油管方向的总重为XXXXkg，此时油管抗拉安全系数为XXXX，抗拉强度满足要求。",
        "jh" : "焦页1-3HF",
        "cookie" : "userName=wlx2023.jhyt; password=; JSESSIONID=FD36F7D78F02B78FD358E69AC28B11D1"
    }
    res = create_JianGuan_word(**para)
    print(res)